package com.fourth.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fourth.bean.UserReturnBean;
import com.fourth.utils.DateFormatUtil;
import com.fourth.utils.MyClickHouseUtil;
import com.fourth.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author YXX
 * @create 2022-08-21 10:07
 */
public class DwsUserLoginWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1.环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //TODO 2.读取Kafka数据
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getFlinkKafkaConsumer("dwd_traffic_page_log", "dws_user_login_window"));

        //TODO 3.转化为JSON,进行数据过滤
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
                JSONObject jsonObject = JSON.parseObject(value);
                String uid = jsonObject.getJSONObject("common").getString("uid");
                String lastPageId = jsonObject.getJSONObject("page").getString("last_page_id");

                if (uid != null && (lastPageId == null || "login".equals(lastPageId))) {
                    out.collect(jsonObject);
                }
            }
        });

        //TODO 4.提取时间戳生成WM
        SingleOutputStreamOperator<JSONObject> DSwithWM = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("ts");
            }
        }));

        //TODO 5.按照Mid分组
        KeyedStream<JSONObject, String> keyedStream = DSwithWM.keyBy(value -> value.getJSONObject("common").getString("uid"));

        //TODO 6.使用状态编程进行去重,转化为JavaBean
        SingleOutputStreamOperator<UserReturnBean> beanDS = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, UserReturnBean>() {

            private ValueState<String> lastLoginDtState;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastLoginDtState = getRuntimeContext().getState(new ValueStateDescriptor<String>("last-login", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<UserReturnBean> out) throws Exception {
                //提取状态日期以及当前数据的日期
                String lastDt = lastLoginDtState.value();
                Long curTs = value.getLong("ts");
                String curDt = DateFormatUtil.toDate(curTs);
                String lastPageId = value.getJSONObject("page").getString("last_page_id");
                //回流用户数
                long backCt = 0L;

                //活跃用户数
                long uuCt = 0L;

                //新增用户
                long insertuu = 0L;

                if (lastPageId == null && "home".equals(value.getJSONObject("page").getString("page_id"))) {
                    insertuu = 1L;
                }

                if (lastDt == null) {
                    lastLoginDtState.update(curDt);
                    if (lastLoginDtState.value().equals(DateFormatUtil.toDate(System.currentTimeMillis()))) {
                        uuCt = 1L;
                        lastLoginDtState.update(curDt);
                    } else {
                        if ((curTs - DateFormatUtil.toTs(lastDt, false) / (24 * 3600 * 1000)) > 7) {
                            backCt = 1L;
                        }
                    }
                }
                //输出数据
                if (uuCt == 1L || insertuu == 1L) {
                    out.collect(new UserReturnBean("", "", backCt, uuCt, insertuu, null));
                }
            }
        });

        //TODO 7.开窗,聚合
        SingleOutputStreamOperator<UserReturnBean> reduce = beanDS.windowAll(TumblingEventTimeWindows.of(Time.days(10)))
                .reduce(new ReduceFunction<UserReturnBean>() {
                    @Override
                    public UserReturnBean reduce(UserReturnBean value1, UserReturnBean value2) throws Exception {
                        value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                        value1.setInsertuu(value1.getInsertuu() + value2.getInsertuu());
                        return value1;
                    }
                }, new AllWindowFunction<UserReturnBean, UserReturnBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<UserReturnBean> values, Collector<UserReturnBean> out) throws Exception {
                        //获取数据
                        UserReturnBean next = values.iterator().next();

                        //补充信息
                        next.setTs(System.currentTimeMillis());
                        next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                        next.setStt(DateFormatUtil.toYmdHms(window.getStart()));

                        //输出数据
                        out.collect(next);
                    }
                });

        //TODO 8.将数据写出到ClickHouse
        reduce.print(">>>>>>>>>>");
        reduce.addSink(MyClickHouseUtil.getSink("insert into dws_user_login_window values(?,?,?,?,?,?)"));

        //TODO 执行
        env.execute();
    }
}
